<template>
	<view class="container" v-if="!loading">
		<view class="main" v-if="goods_list.length">
			<view class="nav">
				<view class="header">
					<view class="left">
						<view class="store-name">
							<text>味特堡</text>
							<view class="iconfont iconarrow-right"></view>
						</view>
					</view>
					<view class="right">
						<view class="dinein" :class="orderType == 'takein'?'active':''" @tap="takein">
							<text>自取</text>
						</view>
						<view class="takeout" :class="orderType == 'takeout'?'active':''" @tap="takout">
							<text>外卖</text>
						</view>
					</view>
				</view>
			</view>
			<view class="content">
				<scroll-view class="menus" :style="'height:' + scrollviewHigh + 'px;'"
					:scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.category_id}`"
							:class="{'current': item.category_id === currentCateId}" v-for="(item, index) in goods_list"
							:key="index" @tap="handleMenuTap(item.category_id)">
							<text>{{ item.name }}</text>
							<view class="dot" v-if="menuCartNum(item.category_id)">{{ menuCartNum(item.category_id) }}
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- goods list begin -->
				<scroll-view class="goods" :style="'height:' + scrollviewHigh + 'px;'" scroll-with-animation scroll-y
					:scroll-top="cateScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<!--<view id="ads"></view>
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>-->
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(item, index) in goods_list" :key="index"
								:id="`cate-${item.category_id}`">
								<view class="title">
									<text>{{ item.name }}</text>
									<!-- <image :src="item.icon" class="icon"></image> -->
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="(good, key) in item.products" :key="key">
										<image :src="good.product_image" class="image"></image>
										<view class="right">
											<text class="name">{{ good.product_name }}</text>
											<text class="tips">{{ good.selling_point }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.product_price }}</text>
												<view class="btn-group" v-if="good.spec_type!=10">
													<button type="primary" class="btn property_btn" hover-class="none"
														size="min" @tap="getProduct(good)">
														选规格
													</button>
													<view class="dot" v-if="good.cart_num!=0">{{good.cart_num}}</view>
												</view>
												<view class="btn-group" v-else>
													<button type="default" v-if="good.cart_num!=0" plain
														class="btn reduce_btn" size="min" hover-class="none"
														@tap="reduceFunc(good)">
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-if="good.cart_num!=0">{{ good.cart_num }}
													</view>
													<button type="primary" class="btn add_btn" size="min"
														hover-class="none" @tap="addCart(good)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
				<!-- goods list end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart_total_num > 0">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ cart_total_num }}</view>
				</view>
				<view class="price">￥{{ total_price }}</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
					去结算
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<prospec :productModel="productModel" :goodDetailModalVisible="goodDetailModalVisible"
			@closeGoodDetailModal="closeGoodDetailModal"></prospec>
		<!-- 购物车详情popup -->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="cart-popup">
					<view class="top">
						<text @tap="handleCartClear">清空</text>
					</view>
					<scroll-view class="cart-list" scroll-y>
						<view class="wrapper">
							<view class="item" v-if="item.total_num >0" v-for="(item, index) in cart_list" :key="index">
								<view class="left">
									<view class="name">{{ item.product_name }}</view>
									<!-- <view class="props">{{ item.props_text }}</view> -->
								</view>
								<view class="center">
									<text>￥{{ item.total_price }}</text>
								</view>
								<view class="right">
									<button type="default" plain size="min" class="btn" hover-class="none"
										@tap="cartReduce(item)">
										<view class="iconfont iconsami-select"></view>
									</button>
									<view class="number">{{ item.total_num }}</view>
									<button type="primary" class="btn" size="min" hover-class="none"
										@tap="cartAdd(item)">
										<view class="iconfont iconadd-select"></view>
									</button>
								</view>
							</view>
							<!--<view class="item" v-if="orderType == 'takeout' && detail.packing_fee">
								<view class="left">
									<view class="name">包装费</view>
								</view>
								<view class="center">
									<text>￥{{ parseFloat(detail.packing_fee) }}</text>
								</view>
								<view class="right invisible">
									<button type="default" plain size="min" class="btn" hover-class="none">
										<view class="iconfont iconsami-select"></view>
									</button>
									<view class="number">1</view>
									<button type="primary" class="btn" size="min" hover-class="none">
										<view class="iconfont iconadd-select"></view>
									</button>
								</view>
							</view>-->
						</view>
					</scroll-view>
				</view>
			</template>

		</popup-layer>
		<!-- 购物车详情popup -->
	</view>
	<view class="loading" v-else>
		<image src="/static/images/loading.gif"></image>
	</view>
</template>

<script>
	import utils from '@/common/utils.js';
	import prospec from './popup/spec.vue';
	import modal from '@/components/modal/modal'
	import popupLayer from '@/components/popup-layer/popup-layer'

	export default {
		components: {
			modal,
			popupLayer,
			prospec
		},
		data() {
			return {
				isLoading:true,
				goods: [], //所有商品
				ads: [],
				loading: true,
				currentCateId: 6905, //默认分类
				cateScrollTop: 0,
				menuScrollIntoView: '',
				cart: [], //购物车
				goodDetailModalVisible: false, //是否饮品详情模态框
				good: {}, //当前饮品
				category: {}, //当前饮品所在分类
				cartPopupVisible: false,
				sizeCalcState: false,
				listData: [],
				goods_list: [],
				productModel: {},
				clock: false,
				cart_total_num: 0,
				total_price: 0,
				cart_list: [],
				orderType: 'takein',
				takeout_address: {},
				phoneHeight: 0,
				/*可滚动视图区域高度*/
				scrollviewHigh: 0,
			}
		},
		onLoad(e) {
			this.orderType = e.orderType
		},
		onShow() {
			let self = this;
			setTimeout(function() {
			self.init();
			self.$fire.on('takeout', function(e) {
				self.takeout_address = e;
				self.orderType = 'takeout'
			})
			}, 300);
			
		},
		computed: {
			menuCartNum() {
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.cate_id === id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			},
		},
		methods: {
			scrollInit() {
				let self = this;
				uni.getSystemInfo({
					success(res) {
						self.phoneHeight = res.windowHeight;
						// 计算组件的高度
						let view = uni.createSelectorQuery().select('.nav');
						view.boundingClientRect(data => {
							let h = self.phoneHeight - data.height;
							self.scrollviewHigh = h;
						}).exec();
					}
				});
			},
			init() { //页面初始化
				this.getCategory();
			},
			firstInit() {
				
				//this.getGoods();
				//this.getCart();
			},
			getCategory() {
				let self = this;
				self.loading = true;
				self.isLoading = true;
				uni.showLoading({
					title: '加载中'
				})
				self._get('product.category/index', {}, function(res) {
					self.goods_list = res.data.list;
					self.loading = false
					self.isLoading = false;
					self.$nextTick(function(){
						self.scrollInit();
					})
					self.getCart();
					uni.hideLoading()
				});
			},
			/*获取数据*/
			getGoods() {
				let self = this;
				self.loading = true;

				self._get('product.product/lists', {}, function(res) {
					self.loading = false
					self.goods_list = res.data.list;
				});
			},
			/*获取数据*/
			getProduct(item) {
				let self = this;
				if (self.clock == true) {
					return
				}
				self.clock = true;
				self.good = item;
				let product_id = item.product_id;
				uni.showLoading({
					title: '加载中'
				})
				self._get(
					'product.product/detail', {
						product_id: product_id,
						url: ''
					},
					function(res) {
						uni.hideLoading();
						/*详情内容格式化*/
						res.data.detail.content = utils.format_content(res.data.detail.content);
						// 初始化商品多规格
						if (res.data.detail.spec_type == 20) {
							self.initSpecData(res.data.specData);
						}
						self.detail = res.data.detail;
						self.showGoodDetailModal()

					}
				);
			},
			/*多规格商品*/
			initSpecData(data) {
				for (let i in data.spec_attr) {
					for (let j in data.spec_attr[i].spec_items) {
						data.spec_attr[i].spec_items[j].checked = false;
					}
				}
				this.specData = data;
				if (this.specData.spec_attr) {
					this.specData.spec_attr.forEach(item => {
						this.alreadyChioce += item.group_name;
						this.alreadyChioce += ' / ';
					});
					this.alreadyChioce = this.alreadyChioce.replace(/(\s\/\s)$/gi, '');
				}
			},
			addCart(item) {
				let self = this;
				let product_id = item.product_id;
				let total_num = 1;
				let product_sku_id = 0;
				let num = 1;
				if (item.product_stock <= item.cart_num) {
					uni.showToast({
						icon: 'none',
						title: "超过限购数量"
					})
					return;
				}
				if (item.product_stock <= 0 || item.product_stock <= item.cart_num) {
					uni.showToast({
						icon: 'none',
						title: '没有更多库存了'
					})
					return;
				}
				self.cart_total_num++
				self.total_price = (self.total_price * 1 + item.product_price * 1).toFixed(2)
				if (item.cart_num) {
					num = item.cart_num + 1
				}
				self.$set(item, 'cart_num', num);
				self._post('order.cart/add', {
					product_id: product_id,
					total_num: total_num,
					product_sku_id: product_sku_id,
				}, function(res) {}, function(err) {});
			},
			reduceFunc(item) {
				let self = this;
				let product_id = item.product_id;
				let num = item.cart_num;
				num--
				self.cart_total_num--
				self.total_price = (self.total_price * 1 - item.product_price * 1).toFixed(2)
				if (num == 0) {
					self._post(
						'order.cart/delete', {
							product_sku_id: item.product_id + "_0"
						},
						function(res) {}
					);
				} else {
					self._post(
						'order.cart/sub', {
							product_id: product_id,
							product_sku_id: 0
						},
						function(res) {},
						function() {}
					);
				}
				self.$set(item, 'cart_num', num);
			},
			getCart() {
				let self = this;
				self._get('order.cart/lists', {
					
				}, function(res) {
					self.isLoading=true;
					self.cart_total_num = res.data.cart_total_num;
					self.total_price = res.data.total_price;
					self.cart_list = res.data.productList;
				});
			},
			cartAdd(goods) {
				let self = this;
				let num = goods.cart_num + 1
				let product_id = goods.product_id;
				let total_num = 1;
				self.cart_total_num++
				self.total_price = (self.total_price * 1 + goods.product_price * 1).toFixed(2);
				let product_sku_id = goods.product_sku_id;
				self._post('order.cart/add', {
					product_id: product_id,
					total_num: total_num,
					product_sku_id: product_sku_id,
				}, function(res) {

				});
				self.goods_list.forEach((item, index) => {
					item.products.forEach((product, product_index) => {
						if (product.product_id == goods.product_id) {
							self.$set(product, 'cart_num', product.cart_num + 1)
						}
					});
				})
				self.$set(goods, 'cart_num', num)
				self.$set(goods, 'total_num', goods.total_num + 1)
				self.$set(goods, 'total_price', (goods.total_price * 1 + goods.product_price * 1).toFixed(2))
			},
			cartReduce(goods) {
				let self = this;
				let product_id = goods.product_id;
				let num = goods.cart_num;
				num--
				self.cart_total_num--
				self.total_price = (self.total_price * 1 - goods.product_price * 1).toFixed(2);
				self.goods_list.forEach((item, index) => {
					item.products.forEach((product, product_index) => {
						if (product.product_id == goods.product_id) {
							self.$set(product, 'cart_num', product.cart_num - 1)
						}
					});
				})
				if (goods.total_num == 1) {
					self._post(
						'order.cart/delete', {
							product_sku_id: goods.product_id + "_" + goods.product_sku_id
						},
						function(res) {}
					);
				} else {
					self._post(
						'order.cart/sub', {
							product_id: goods.product_id,
							product_sku_id: goods.product_sku_id
						},
						function(res) {},
						function() {}
					);
				}
				self.$set(goods, 'cart_num', num);
				self.$set(goods, 'total_price', (goods.total_price * 1 - goods.product_price * 1).toFixed(2))
				self.$set(goods, 'total_num', goods.total_num - 1)
			},
			takout() {
				if (this.orderType == 'takeout') return
				this.orderType = 'takeout'
			},
			takein() {
				if (this.orderType == 'takein') return
				this.orderType = 'takein'
			},
			handleMenuTap(id) { //点击菜单项事件
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				this.currentCateId = id;

				this.$nextTick(() => this.cateScrollTop = this.goods_list.find(item => item.category_id == id).top);
			},
			handleGoodsScroll({
				detail
			}) { //商品列表滚动事件
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				const {
					scrollTop
				} = detail;
				let tabs = this.goods_list.filter(item => item.top <= scrollTop).reverse();
				if (tabs.length > 0) {
					this.currentCateId = tabs[0].category_id
				}
			},
			calcSize() {
				let h = 10;

				/*let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()*/

				this.goods_list.forEach(item => {
					let view = uni.createSelectorQuery().select(`#cate-${item.category_id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h;
						h += data.height;
						item.bottom = h;
					}).exec()
				})
				this.sizeCalcState = true
			},
			showGoodDetailModal() {
				let obj = {
					specData: this.specData,
					detail: this.detail,
					productSpecArr: this.specData != null ? new Array(this.specData.spec_attr.length) : [],
					show_sku: {
						sku_image: '',
						seckill_price: 0,
						product_sku_id: 0,
						line_price: 0,
						seckill_stock: 0,
						seckill_product_sku_id: 0,
						sum: 1
					},
					type: 'card'
				};
				this.productModel = obj;
				this.goodDetailModalVisible = true;
			},
			closeGoodDetailModal(num, price) { //关闭饮品详情模态框
				this.goodDetailModalVisible = false
				this.clock = false;
				if (num) {
					this.$set(this.good, 'cart_num', this.good.cart_num ? this.good.cart_num + num : num);
					this.cart_total_num = this.cart_total_num + num;
					this.total_price = this.total_price * 1 + price * num;
				}
				this.category = {}
				this.good = {}
			},
			openCartPopup() { //打开/关闭购物车列表popup
				this.getCart();
				this.cartPopupVisible = !this.cartPopupVisible
			},
			handleCartClear() { //清空购物车
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定清空购物车么',
					success() {
						self.clearCart()
					}
				})
			},
			clearCart() {
				let self = this;
				self._post(
					'order.cart/clear', {},
					function(res) {
						self.cartPopupVisible = false;
						self.cart_list = [];
						self.getCategory()
					}
				);
			},
			toPay() {
				let self = this;
				uni.showLoading({
					title: '加载中'
				})
				self._get('order.cart/lists', {}, function(res) {
					self.cart_total_num = res.data.cart_total_num;
					self.total_price = res.data.total_price;
					self.cart_list = res.data.productList;
					let arrIds = [];
					self.cart_list.forEach(item => {
						arrIds.push(`${item.product_id}_${item.product_sku_id}`);
					});
					if (arrIds.length == 0) {
						uni.showToast({
							title: '请选择商品',
							icon: 'none'
						});
						return false;
					}
					let delivery = self.orderType == "takeout" ? 10 : 20;
					uni.hideLoading()
					uni.navigateTo({
						url: '/pages/order/confirm-order?order_type=cart&cart_ids=' + arrIds +
							'&delivery=' + delivery
					});

				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '~@/pages/menu/menu.scss';

	.good-detail-modal {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;

		.detail {
			width: 100%;
			min-height: 1vh;
			max-height: calc(90vh - 320rpx - 80rpx - 120rpx);

			.wrapper {
				width: 100%;
				height: 100%;
				overflow: hidden;

			}
		}
	}

	.good_basic {
		padding: 0 20rpx 30rpx;
		display: flex;
		flex-direction: column;

		.name {
			font-size: $font-size-base;
			color: $text-color-base;
			margin-bottom: 10rpx;
		}

		.tips {
			font-size: $font-size-sm;
			color: $text-color-grey;
		}
	}

	.cover {
		height: 320rpx;
		padding: 30rpx 0;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;

		.image {
			width: 260rpx;
			height: 260rpx;
		}

		.btn-group {
			position: absolute;
			right: 10rpx;
			top: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;

			image {
				width: 80rpx;
				height: 80rpx;
			}
		}
	}

	.properties {
		width: 100%;
		border-top: 2rpx solid $bg-color-grey;
		padding: 10rpx 30rpx 0;
		display: flex;
		flex-direction: column;
	}

	.property {
		width: 100%;
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;
		padding-bottom: -16rpx;

		.title {
			width: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin-bottom: 20rpx;

			.name {
				font-size: 26rpx;
				color: $text-color-base;
				margin-right: 20rpx;
			}

			.desc {
				flex: 1;
				font-size: $font-size-sm;
				color: $color-primary;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.values {
			width: 100%;
			display: flex;
			flex-wrap: wrap;

			.value {
				border-radius: 8rpx;
				background-color: $bg-color-grey;
				padding: 16rpx 30rpx;
				font-size: 26rpx;
				color: $text-color-assist;
				margin-right: 16rpx;
				margin-bottom: 16rpx;

				&.default {
					background-color: $color-primary;
					color: $text-color-white;
				}
			}
		}
	}

	.action {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: $bg-color-grey;
		height: 120rpx;
		padding: 0 26rpx;

		.left {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
			margin-right: 20rpx;
			overflow: hidden;

			.price {
				font-size: $font-size-lg;
				color: $text-color-base;
			}

			.props {
				color: $text-color-assist;
				font-size: 24rpx;
				width: 100%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.btn-group {
			display: flex;
			align-items: center;
			justify-content: space-around;

			.number {
				font-size: $font-size-base;
				width: 44rpx;
				height: 44rpx;
				line-height: 44rpx;
				text-align: center;
			}

			.btn {
				padding: 0;
				font-size: $font-size-base;
				width: 44rpx;
				height: 44rpx;
				line-height: 44rpx;
				border-radius: 100%;
			}
		}
	}

	.add-to-cart-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: $color-primary;
		color: $text-color-white;
		font-size: $font-size-base;
		height: 80rpx;
		border-radius: 0 0 12rpx 12rpx;
	}

	.cart-popup {
		.top {
			background-color: $bg-color-primary;
			color: $color-primary;
			padding: 10rpx 30rpx;
			font-size: 24rpx;
			text-align: right;
		}

		.cart-list {
			background-color: #FFFFFF;
			width: 100%;
			overflow: hidden;
			min-height: 1vh;
			max-height: 60vh;

			.wrapper {
				height: 100%;
				display: flex;
				flex-direction: column;
				padding: 0 30rpx;
				margin-bottom: 156rpx;

				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx 0;
					position: relative;

					&::after {
						content: ' ';
						position: absolute;
						bottom: 0;
						left: 0;
						width: 100%;
						background-color: $border-color;
						height: 2rpx;
						transform: scaleY(.6);
					}

					.left {
						flex: 1;
						display: flex;
						flex-direction: column;
						overflow: hidden;
						margin-right: 30rpx;

						.name {
							font-size: $font-size-sm;
							color: $text-color-base;
						}

						.props {
							color: $text-color-assist;
							font-size: 24rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}

					.center {
						margin-right: 120rpx;
						font-size: $font-size-base;
					}

					.right {
						display: flex;
						align-items: center;
						justify-content: space-between;

						.btn {
							width: 46rpx;
							height: 46rpx;
							border-radius: 100%;
							padding: 0;
							text-align: center;
							line-height: 46rpx;
						}

						.number {
							font-size: $font-size-base;
							width: 46rpx;
							height: 46rpx;
							text-align: center;
							line-height: 46rpx;
						}
					}
				}
			}
		}
	}
</style>
